//
//  ATLoginViewController.m
//  Adorable_Things
//
//  Created by huzhiyan on 16/1/16.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ATLoginViewController.h"
#import "BQHtmlViewController.h"
#import "ATRegisterViewController.h"
#import "Utils.h"
#import "MBProgressHUD.h"

@interface ATLoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UINavigationController *naVC;


@end

@implementation ATLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self addNavigationControl];
    [self setSubViewSize];
}

#pragma mark --- 设置自定义导航栏navigationControl
- (void)addNavigationControl
{
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-568h@2x"]];
    
    UIView *navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 64)];
    navigationView.backgroundColor = [UIColor whiteColor];
    UIButton *cancelButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    cancelButton.frame = CGRectMake(20, 25, 50, 35);
    [cancelButton setTitle:@"取消" forState:(UIControlStateNormal)];
    [cancelButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [navigationView addSubview:cancelButton];
    
    UIButton *loginButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    loginButton.frame = CGRectMake((kWidth - 50) / 2, 17, 50, 45);
    [loginButton setTitle:@"登录" forState:(UIControlStateNormal)];
    [loginButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:24];
    [navigationView addSubview:loginButton];
    
    UIButton *registerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    registerButton.frame = CGRectMake(kWidth - 70, 25, 50, 35);
    [registerButton setTitle:@"注册" forState:(UIControlStateNormal)];
    [registerButton setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [registerButton addTarget:self action:@selector(registerButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [navigationView addSubview:registerButton];
    [self.view addSubview:navigationView];
    
    // 添加登录button方法
    [_loginButton addTarget:self action:@selector(loginButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    // 添加忘记密码button方法
    [_forgetPassword addTarget:self action:@selector(forgetPasswordClick:) forControlEvents:(UIControlEventTouchUpInside)];
    // 添加协议button方法
    [_protocolButton addTarget:self action:@selector(protocolButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    // 添加微博第三方登陆
    [_twitterButton addTarget:self action:@selector(twitterButtonLoginClick:) forControlEvents:(UIControlEventTouchUpInside)];
    // 添加微信第三方登陆
    [_weChatButton addTarget:self action:@selector(weChatButtonLoginClick:) forControlEvents:(UIControlEventTouchUpInside)];
    // 添加QQ第三方登陆
    [_QQButton addTarget:self action:@selector(QQButtonLoginClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

#pragma mark --- 自定义导航栏 注册,取消button点击方法实现
- (void)cancelButtonClick:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)registerButtonClick:(UIButton *)button
{
    ATRegisterViewController *registerVC = [[ATRegisterViewController alloc] init];
    registerVC.myTitle = @"注册";
    [self.navigationController pushViewController:registerVC animated:YES];
}

#pragma mark --- 登录button点击方法实现
- (void)loginButtonClick:(UIButton *)button
{
    // 判断手机号码数字对不对
    
    if (![Utils checkTelNumber:_nameTF.text]) {
        [self createMBProgressHUD:@"您输入的手机号码不正确"];
    } else if (_passwordTF.text.length < 6) {
        [self createMBProgressHUD:@"密码最少为6位"];
    } else {
        [self setLoginRequest];
       [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

#pragma mark --- 忘记密码button点击方法实现
- (void)forgetPasswordClick:(UIButton *)button
{
    ATRegisterViewController *registerVC = [[ATRegisterViewController alloc] init];
    registerVC.myTitle = @"忘记密码";
    [self.navigationController pushViewController:registerVC animated:YES];
}

#pragma mark --- 创建,取消UIAlertController
- (void)createMBProgressHUD:(NSString *)title
{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // 只显示文字
    HUD.mode = MBProgressHUDModeText;
    [self.view addSubview:HUD];
    
    //如果设置此属性则当前的view置于后台
    HUD.dimBackground = YES;
    
    //设置对话框文字
    HUD.labelText = title;
    
    //显示对话框
    [HUD showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(2);
    } completionBlock:^{
        //操作执行完后取消对话框
        [HUD removeFromSuperview];
    }];

}


#pragma mark --- 账号密码登陆请求数据
- (void)setLoginRequest
{
    ATUserManager *UserManager = [ATUserManager shareManager];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"password"] = _passwordTF.text;
    dic[@"phone"] = _nameTF.text;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://api.menghuoapp.com/v1/user/login" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *msg = responseObject[@"msg"];
        
        if ([msg isEqualToString:@"账号不存在"]) {
            [self createMBProgressHUD:msg];
        } else if ([msg isEqualToString:@"密码错误"]) {
            [self createMBProgressHUD:msg];
        } else if ([msg isEqualToString:@"OK"]) {
            UserManager.auth_token = responseObject[@"data"];
            NSDictionary *pardic = @{@"auth_token":UserManager.auth_token};
            [manager POST:@"http://api.menghuoapp.com/v1/user/profile" parameters:pardic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                UserManager.isLogin = 1;
                UserManager.nickname = responseObject[@"data"][@"nickname"];
                UserManager.avatar = responseObject[@"data"][@"avatar"];
                // 写入文件
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                dic[@"isLogin"] = [NSString stringWithFormat:@"%ld",UserManager.isLogin];
                dic[@"auth_token"] = UserManager.auth_token;
                
                [dic writeToFile:kUserInfor atomically:YES];
                // 登陆成功后模态回上一个界面
                [self createMBProgressHUD:@"登录成功"];
//                self.loginBlock();
                [self dismissViewControllerAnimated:YES completion:nil];

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
                   }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark --- 第三方微博登录点击方法实现
- (void)twitterButtonLoginClick:(UIButton *)button
{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //          获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
             ATUserManager *UserManager = [ATUserManager shareManager];
            UserManager.nickname = snsAccount.userName;
            UserManager.auth_token = snsAccount.accessToken;
            UserManager.isLogin = 1;
            // 写入文件
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"isLogin"] =@"1";
            dic[@"auth_token"] = snsAccount.accessToken;
            [dic writeToFile:kUserInfor atomically:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }});
}

#pragma mark --- 第三方微信登录点击方法实现
- (void)weChatButtonLoginClick:(UIButton *)button
{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
            ATUserManager *UserManager = [ATUserManager shareManager];
            UserManager.nickname = snsAccount.userName;
            UserManager.auth_token = snsAccount.accessToken;
            UserManager.isLogin = 1;
            // 写入文件
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"isLogin"] =@"1";
            dic[@"auth_token"] = snsAccount.accessToken;
            [dic writeToFile:kUserInfor atomically:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    });
}

#pragma mark --- 第三方QQ登录点击方法实现
- (void)QQButtonLoginClick:(UIButton *)button
{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //          获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            ATUserManager *UserManager = [ATUserManager shareManager];
            UserManager.nickname = snsAccount.userName;
            UserManager.auth_token = snsAccount.accessToken;
            UserManager.isLogin = 1;
            // 写入文件
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"isLogin"] =@"1";
            dic[@"auth_token"] = snsAccount.accessToken;
            [dic writeToFile:kUserInfor atomically:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }});

}

#pragma mark --- 协议button点击方法实现
- (void)protocolButtonClick:(UIButton *)button
{
    BQHtmlViewController *HtmlVC = [[BQHtmlViewController alloc] init];
    HtmlVC.urlStr = @"http://m.menghuoapp.com/agreement.html";
    HtmlVC.myTitle = @"用户使用协议";
    [self.navigationController pushViewController:HtmlVC animated:YES];
}

- (void)setSubViewSize
{
    _barkgroundView.layer.cornerRadius = 10;
    _loginButton.layer.cornerRadius = 20;
    _nameTF.delegate = self;
    _nameTF.keyboardType = UIKeyboardTypePhonePad;
    _passwordTF.secureTextEntry = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
